<template>
  <div class="start-node-dialog">
    <el-dialog
      v-model="dialogVisible"
      width="527"
      modal-class="custom-dialog"
      :close-on-click-modal="false"
      :append-to-body="true"
      :destroy-on-close="true"
      :title="pageType === PageTypeEnum.ADD ? '新增变量' : '编辑变量'"
    >
      <el-form
        ref="RuleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="80"
        class="custom-form"
      >
        <el-form-item label="变量名" prop="label">
          <el-input
            v-model.trim="ruleForm.label"
            :disabled="builtInVariables.includes(ruleForm.variable)"
            placeholder="给变量设置一个中文名"
          />
        </el-form-item>
        <el-form-item label="变量key" prop="variable">
          <el-input
            v-model.trim="ruleForm.variable"
            :disabled="builtInVariables.includes(ruleForm.variable)"
            placeholder="请输入变量key"
          />
        </el-form-item>
        <el-form-item label="字段描述" prop="description">
          <el-input v-model.trim="ruleForm.description" placeholder="请输入字段描述" />
        </el-form-item>
        <el-form-item
          v-if="!builtInVariables.includes(ruleForm.variable)"
          label="变量类型"
          prop="type"
        >
          <el-radio-group v-model="ruleForm.type" class="custom-checkbox" @change="resetItem">
            <template v-for="item in VariableList" :key="item.value">
              <el-radio-button :label="item.value" v-if="item.value !== 'file'">
                {{ item.name }}
              </el-radio-button>
            </template>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!builtInVariables.includes(ruleForm.variable)">
          <div class="type-box">
            <div v-if="ruleForm.type === VariableTypeEnum.TEXT">
              <el-form-item label="最大长度" prop="max_length" style="margin-bottom: 16px">
                <el-input v-model.trim="ruleForm.max_length" placeholder="请输入最大长度" />
              </el-form-item>
              <el-form-item
                label="默认值"
                prop="value"
                :rules="[
                  { required: true, message: '请输入默认值', trigger: 'change' },
                  {
                    min: 1,
                    max: ruleForm.max_length,
                    message: `最大长度为1-${ruleForm.max_length}个字符`,
                    trigger: 'change'
                  }
                ]"
              >
                <el-input v-model.trim="ruleForm.value" placeholder="请输入默认值" />
              </el-form-item>
            </div>
            <template v-if="ruleForm.type === VariableTypeEnum.NUMBER">
              <el-form-item
                label="默认值"
                prop="value"
                :rules="[
                  { required: true, message: '请输入默认值', trigger: 'change' },
                  {
                    validator: IsValidOneNumber,
                    trigger: 'change',
                    required: true
                  }
                ]"
              >
                <el-input v-model.trim="ruleForm.value" placeholder="请输入默认值" />
              </el-form-item>
            </template>
            <div v-if="ruleForm.type === VariableTypeEnum.SINGLE" style="margin-right: -10px">
              <div v-for="(item, index) in ruleForm.enums" :key="item.key" class="flex-space">
                <el-form-item
                  style="margin-bottom: 16px; flex: 1; margin-right: 4px"
                  label-width="80"
                  :prop="'enums.' + index + '.value'"
                  :label="index === 0 ? '枚举值' : ''"
                  :rules="[
                    {
                      required: true,
                      message: '请输入枚举值',
                      trigger: 'change'
                    },
                    { min: 1, max: 100, message: '枚举值为1-100个字符', trigger: 'change' }
                  ]"
                >
                  <el-input v-model.trim="item.value" placeholder="请输入枚举值" />
                </el-form-item>
                <el-form-item style="height: 32px; line-height: 32px; width: 16px">
                  <el-link
                    :underline="false"
                    type="primary"
                    v-if="ruleForm.enums.length > 1"
                    @click="ruleForm.enums.splice(index, 1)"
                  >
                    <el-icon><Close /></el-icon>
                  </el-link>
                </el-form-item>
              </div>
              <el-form-item label-width="80" style="margin-right: 18px">
                <el-button type="primary" class="custom-btn" @click="addEnum">
                  <el-icon style="margin-right: 8px"><Plus /></el-icon>
                  新增枚举值
                </el-button>
              </el-form-item>
            </div>
            <template v-if="ruleForm.type === VariableTypeEnum.DATE">
              <el-form-item label="最大间隔" prop="max_length" style="margin-bottom: 16px">
                <el-input
                  v-model.trim="ruleForm.max_length"
                  placeholder="请输入最大长度"
                  class="max-len-input"
                  @input="ruleForm.value = []"
                >
                  <template #append>天</template>
                </el-input>
              </el-form-item>
              <el-form-item
                label="默认值"
                prop="value"
                :rules="[{ required: true, message: '请输入默认值', trigger: 'change' }]"
              >
                <el-date-picker
                  style="width: calc(100% - 20px)"
                  v-model="ruleForm.value"
                  type="daterange"
                  range-separator="~"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  :disabledDate="disabledDate"
                  @calendar-change="calendarChange"
                />
              </el-form-item>
            </template>
            <template v-if="ruleForm.type === VariableTypeEnum.OBJECT">
              <el-form-item
                label="默认值"
                prop="value"
                :rules="[{ required: true, message: '请输入默认值', trigger: 'change' }]"
              >
                <el-input v-model.trim="ruleForm.value" placeholder="请输入默认值" />
              </el-form-item>
            </template>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex-space">
          <el-form
            ref="RequiredRuleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="52"
            class="custom-form"
          >
            <el-form-item label="必填" prop="required" style="margin-bottom: 0">
              <el-switch
                :active-value="RequiredTypeEnum.YES"
                :inactive-value="RequiredTypeEnum.NO"
                v-model="ruleForm.required"
                size="small"
                :disabled="builtInVariables.includes(ruleForm.variable)"
              />
            </el-form-item>
          </el-form>
          <div>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submit(RuleFormRef)">确定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="StartNodeDialog">
import { ref, reactive } from 'vue';
import type { FormRules } from 'element-plus';
import { FormInstance } from 'element-plus';
import {
  builtInVariables,
  nanoId, RequiredTypeEnum,
  StartNodeInputVariables,
  StartNodeInputVariablesItem,
  VariableList,
  VariableTypeEnum
} from '@/view/graph/model/type';
import {IsValidIdentifier, IsValidInputNumber, IsValidOneNumber} from '@/utils/validate/validate';
import {PageTypeEnum} from '@/utils/public-model/public-model';

const emits = defineEmits(['saveVariable']);

const RuleFormRef = ref();
const RequiredRuleFormRef = ref();

const ruleForm = ref<StartNodeInputVariables>({
  ...StartNodeInputVariablesItem,
  id: nanoId(),
  enums: [{ key: nanoId(), value: '' }]
});

const rules = reactive<FormRules<StartNodeInputVariables>>({
  label: [
    { required: true, message: '请输入变量名', trigger: 'change' },
    { min: 1, max: 100, message: '变量名长度为1-100个字符', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入字段描述', trigger: 'change' },
    { min: 1, max: 50, message: '字段描述长度为1-50个字符', trigger: 'change' }
  ],
  variable: [
    { required: true, message: '请输入变量key', trigger: 'change' },
    { validator: IsValidIdentifier, trigger: 'change' }
  ],
  type: [{ required: true, message: '请选择变量类型', trigger: 'change' }],
  required: [{ required: true, message: '请选择必填', trigger: 'change' }],
  max_length: [
    { required: true, message: '请输入最大长度', trigger: 'change' },
    { validator: IsValidInputNumber, trigger: 'change' }
  ]
});

const dialogVisible = ref(false);
const pageType = ref();
const choiceDate = ref();

/**
 * 初始化
 * @param type
 * @param startNodeInputVariable
 */
function init(type: string, startNodeInputVariable?: StartNodeInputVariables) {
  dialogVisible.value = true;
  pageType.value = type;
  if (pageType.value === PageTypeEnum.EDIT) {
    ruleForm.value = startNodeInputVariable as StartNodeInputVariables;
    if (ruleForm.value.type === VariableTypeEnum.DATE) {
      const value = ruleForm.value.value as string;
      ruleForm.value.value = value.split(',');
    }
  } else {
    ruleForm.value = {
      ...StartNodeInputVariablesItem,
      id: nanoId(),
      enums: [{ key: nanoId(), value: '' }]
    };
  }
}

/**
/**
 * 添加枚举值
 */
function addEnum() {
  ruleForm.value.enums.push({ key: nanoId(), value: '' });
}

/**
 * 获取时间参数
 * @param obj
 */
const calendarChange = (obj: [Date, null | Date]) => {
  const minDate = obj[0];
  const maxDate = obj[1];
  // 把选择的第一个日期赋值给一个变量。
  choiceDate.value = minDate.getTime();
  // 如何你选择了两个日期了，就把那个变量置空
  if (maxDate) {
choiceDate.value = null;
}
};

/**
 * 时间禁用
 * @param date
 */
function disabledDate(date: Date) {
  if (!ruleForm.value.max_length || !choiceDate.value) {
    return false;
  }
  // 7天的时间戳
  const one = ruleForm.value.max_length * 24 * 3600 * 1000;
  // 当前日期 - one = 7天之前
  const minTime = choiceDate.value - one;
  // 当前日期 + one = 7天之后
  const maxTime = choiceDate.value + one;
  return date.getTime() < minTime || date.getTime() > maxTime;
}

/**
 * 切换类型初始化参数
 */
function resetItem() {
  ruleForm.value.max_length = 20;
  if (ruleForm.value.type === VariableTypeEnum.DATE) {
    ruleForm.value.value = [];
  } else {
    ruleForm.value.value = '';
  }
  ruleForm.value.enums = [{ key: nanoId(), value: '' }];
}

/**
 * 保存
 */
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
return;
}
  let flag = false;
  await RequiredRuleFormRef.value.validateField('required', (isValid: boolean) => {
    if (isValid) {
      flag = true;
    }
  });
  await formEl.validate(valid => {
    if (valid && flag) {
      const newForm = {
        ...ruleForm.value
      };
      if (newForm.type === VariableTypeEnum.DATE) {
        const value = newForm.value as Array<string>;
        newForm.value = value.join(',');
      }
      emits('saveVariable', newForm, pageType.value);
    }
  });
};

defineExpose({
  init,
  dialogVisible
});
</script>

<style scoped lang="scss">
.type-box {
  background: rgba(42, 48, 58, 0.03);
  padding: 16px;
  flex: 1;
}
.fixation-btn {
  position: absolute;
  bottom: 24px;
  width: calc(100% - 32px - 80px);
}
</style>
